package com.app.island.cash.requestview

import android.text.TextUtils
import androidx.appcompat.app.AppCompatActivity
import com.app.island.cash.databinding.EnterForgetPasswordActBinding
import com.app.island.cash.data.sigle.OTPCall
import com.app.island.cash.data.sigle.ResetPwdCall
import com.app.island.cash.requestwork.AppService
import com.app.island.cash.requestwork.HttpResult
import com.app.island.cash.requestwork.NetClient
import com.app.island.cash.requestwork.RequestCallBack
import com.app.island.cash.utilstools.NetWorkLoadingUtil
import com.app.island.cash.utilstools.SystemUtils
import com.app.island.cash.utilstools.ToastUtil

class EnterForgetPwdActReq {
    private var context: AppCompatActivity
    private var binding: EnterForgetPasswordActBinding
    private var phone: String

    constructor(context: AppCompatActivity, binding: EnterForgetPasswordActBinding, phone: String) {
        this.context = context
        this.binding = binding
        this.phone = phone
        setCliclk()
    }

    private fun setCliclk() {
        binding.timeButton.setLength(60)
        binding.timeButton.setOnClickListener { sendSMS() }
        binding.btnReset.setOnClickListener { forgetUPwd() }
        binding.ivFinish.setOnClickListener { context.finish() }
        binding.tvPageTitle.text = "Retrieve Password"
        binding.phoneEdit.setText(phone)
    }

    private fun forgetUPwd() {
        val otp: String = binding.tvOtp.text.toString()
        val pwd: String = binding.password.text.toString()
        val phone: String = binding.phoneEdit.text.toString()
        if (TextUtils.isEmpty(phone)) {
            ToastUtil.toast("please enter phone number")
            return
        }
        if (TextUtils.isEmpty(otp)) {
            ToastUtil.toast("please enter otp first")
            return
        }
        if (pwd.length < 6) {
            ToastUtil.toast("password length is 6~16")
            return
        }
        val call = ResetPwdCall()
        call.confirmPassword = SystemUtils.md5(pwd)
        call.newPwd = SystemUtils.md5(pwd)
        call.phone = phone
        call.vcode = otp
        val resultCall = NetClient.getService(
            AppService::class.java
        ).resetPwd(call)
        resultCall.enqueue(object : RequestCallBack<HttpResult<Any>?>() {
           override fun onSuccess(body: HttpResult<Any>?) {
                ToastUtil.toast(body?.msg)
                context.finish()
            }
        })
    }

    private fun sendSMS() {
        NetWorkLoadingUtil.showDialog(context)
        val call = OTPCall(phone, "", "findReg")
        NetClient.getService(
            AppService::class.java
        ).sendSms(call).enqueue(object : RequestCallBack<HttpResult<Any>?>() {
            override fun onSuccess(body: HttpResult<Any>?) {
                binding.timeButton.runTimer()
            }
        })
    }
}